package com.jarchie.androiddev.ui.views

import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.ImageView
import com.jarchie.androiddev.databinding.LayoutListWrapperPlayerViewBinding
import com.jarchie.androiddev.ext.setBlurImageUrl
import com.jarchie.androiddev.ext.setImageUrl
import com.jarchie.androiddev.ext.setVisibility
import com.jarchie.androiddev.utils.DisplayUtil

/**
 * 用于动态挂载视频播放控制器和显示视频画面的PlayerView
 */
class WrapperPlayerView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null,defStyleAttr: Int=0,defStyleRes: Int = 0
) : FrameLayout(context, attrs) {
    val viewBinding = LayoutListWrapperPlayerViewBinding.inflate(LayoutInflater.from(context),this)



    fun bindData(widthPx:Int,heightPx:Int,coverUrl: String?,videoUrl: String,maxHeight: Int){
        viewBinding.cover.setImageUrl(coverUrl)
        if (widthPx < heightPx){
            coverUrl?.run {
                viewBinding.blurBackground.setBlurImageUrl(this,10)
                viewBinding.blurBackground.setVisibility(true)
            }
        }else{
            viewBinding.blurBackground.setVisibility(false)
        }

        setSize(widthPx,heightPx, DisplayUtil.getScreenWidth(),maxHeight)
    }

    private fun setSize(widthPx: Int, heightPx: Int, maxWidth: Int, maxHeight: Int) {
        val converWidth: Int
        val converHeight: Int
        if (widthPx >= heightPx){
            converWidth = maxWidth
            converHeight = (heightPx/(widthPx*1.0f/maxWidth)).toInt()
        }else{
            converHeight = maxHeight
            converWidth = (widthPx/(heightPx*1.0f/maxHeight)).toInt()
        }
        val wrapperViewParams = layoutParams
        wrapperViewParams.width = maxWidth
        wrapperViewParams.height = converHeight
        layoutParams = wrapperViewParams

        val blurParams = viewBinding.blurBackground.layoutParams
        blurParams.width= maxWidth
        blurParams.height = converHeight
        viewBinding.blurBackground.layoutParams = blurParams

        val coverParams: LayoutParams = viewBinding.cover.layoutParams as LayoutParams
        coverParams.width = converWidth
        coverParams.height = converHeight
        coverParams.gravity = Gravity.CENTER
        viewBinding.cover.scaleType = ImageView.ScaleType.FIT_CENTER
        viewBinding.cover.layoutParams = coverParams

    }
}